package com.xia.im.netty.quickstart;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * netty基础模版，服务器端
 */
@Slf4j
public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        //线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try{
            //服务启动器
            ServerBootstrap bootstrap = new ServerBootstrap();
            //设置两个线程组
            bootstrap.group(bossGroup,workerGroup);
            //NioServerSocketChannel作为管道实现
            bootstrap.channel(NioServerSocketChannel.class);
            // 设置线程队列等待连接的个数（最大连接数）
            bootstrap.option(ChannelOption.SO_BACKLOG,128);
            // 设置保持活动连接状态（TCP心跳机制）
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
            // 给workerGroup的EventLoop对应的管道设置处理器
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    log.info("客户端channel 初始化");
                    // 将自定义的处理器添加到管道中
                    ch.pipeline().addLast(new NettyServerHandler());

                }
            });

            // 绑定端口并启动服务器（同步操作）
            ChannelFuture cf = bootstrap.bind(9999).sync();
            log.info("服务启动成功....");
            // 添加监听器，查看绑定端口是否成功
            cf.addListener((ChannelFutureListener) future -> {
                log.info("监听端口:{}", future.isSuccess());
            });
            // 对关闭通道进行监听（同步操作）
            cf.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }
}
